/*
 * @Date: 2022-09-23 14:34:01
 * @LastEditTime: 2023-02-07 11:14:00
 * @Description: 路由
 */
import { createRouter, createWebHashHistory, createWebHistory, RouteRecordRaw } from 'vue-router'
import { useRouterStore } from '@/store/modules/router';
import {useUserStore} from "@/store/modules/user";

//默认页面路由
const defaultRoutes: Array<RouteRecordRaw> = [
  {
    path: '/login',
    name: 'Login',
    // component: () => import('@/views/common/Login/login.vue')
    component: () => import('@/views/common/Login')
  },
  {
    name: 'Redirect',
    path: '/redirect/:path(.*)',
    component: () => import('@/views/common/redirect'),
    meta: {
      hidden: true,
      title: '重定向'
    }
  },
  {
    path: '/404',
    name: 'NotFound',
    component: () => import('@/views/common/Error')
  }
]

//登陆后基础页面路由
const businessRouter: Array<RouteRecordRaw> = [
  {
    path: "/singleHome",
    name: "singleHome",
    component: () => import('@/views/common/Home/singleHome'),
    children: [
      {
        path: 'sjdx',
        name: 'singleSjdx',
        component: () => import('@/components/Sjdx')
      },
    ]
  },
  {
    path: "/",
    name: "Home",
    component: () => import('@/views/common/Home'),
    children: [
      {
        path: 'sjdx',
        name: 'Sjdx',
        component: () => import('@/components/Sjdx'),
        children: [{
          path: 'myMenu',
          name: 'myMenu',
          component: () => import('@/components/Sjdx')
        }
        ]
      },
    ]
  }]

const errorRouter: Array<RouteRecordRaw> = [
  { // 当没有匹配到正确路由的时候，匹配notOpen组件
    path: '/:pathMatch(.*)*',   // 这个地方做了一个路由匹配。如果没有，则跳转到LoginOut组件里面
    component: () => import('@/views/common/Error'),
    meta: {
      footShow: false // true显示，false隐藏
    }
  }]

const router = createRouter({
  history: createWebHashHistory(),
  routes: defaultRoutes,
})

// @router/routers.ts 中添加前置路由守卫
router.beforeEach(async (to, from, next) => {
  // 注意：在beforeEach中调用pinia存储的菜单状态是为了避免` Did you forget to install pinia?`这个bug
  const routerStore = useRouterStore()
  console.log('hasRoute', routerStore.hasRoute)
  if (to.path === '/login' || to.path === '/404') {
    next()
  } else if (!routerStore.hasRoute) {
    await routerStore.setRouter(true)
    next(to)
  }else {
    if (to.path == '/' || to.path == ''|| to.path == '/'+useUserStore().getCurrentSystemCode) {
      let menuTree = routerStore.getMenuTree;
      if(menuTree.length==0){
        next('/login');
        return;
      }
      next(routerStore.getIndex(menuTree[0]))
    } else {
      next()
    }
  }
})

export { businessRouter, errorRouter }

export default router
